import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class MainBaozoumanhua {
	public static final String STARTPAGE = "http://baozoumanhua.com/latest/page/1117";
	public static final String PAGE_PATTERN = "http://baozoumanhua.com/latest/page/";
	public static final int START_PAGE_NUMBER = 1117;
	public static int currentPageNumber = 0;
	public static final String DOMAIN = "http://baozoumanhua.com";

	public static String toURL(String url) {
		if (url.toLowerCase().startsWith("http://")) {
			return url;
		} else {
			return DOMAIN + url;
		}
	}

	public static String saveTo = null;
	static {
		saveTo = "E:\\Android\\暴走漫画系列\\autodownload\\baozoumanhua\\"
				+ new Date().getTime() + "\\";
		File f = new File(saveTo);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	public static void main(String[] args) throws MalformedURLException, IOException  {
		currentPageNumber = START_PAGE_NUMBER;
		String startPageURL = pageNumberToPageURL(currentPageNumber);
		Document doc = Jsoup.parse(new URL(startPageURL), 1000 * 30);
		while (true) {
				Elements imageElements = doc.select("div.thumb img");
				for (int i = 0; i < imageElements.size(); i++) {
					Element element = imageElements.get(i);
					String title = element.attr("alt");
					String imageURL = element.attr("src");
					try {
						downloadImage(imageURL, title);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				System.out.println("=================");
				if (currentPageNumber <= 1) {
					break;
				}
				String nextPageUrl = nextPageURL();
				System.out.println("page:" + nextPageUrl);
				try {
					URL nextPageURL = new URL(nextPageUrl);
					doc = Jsoup.parse(nextPageURL, 1000 * 30);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

	private static String pageNumberToPageURL(int number) {
		return PAGE_PATTERN + Integer.valueOf(number).toString();
	}

	private static String nextPageURL() {
		currentPageNumber--;
		return pageNumberToPageURL(currentPageNumber);
	}


	private static String parseTitle(Element titleElement) {
		if (titleElement == null) {
			return "";
		}
		String title = titleElement.text();
		if (title.indexOf("-") > -1) {
			title = title.substring(title.indexOf("-") + 1, title.length())
					.trim();
		}
		title = title.replaceAll("<", "");
		title = title.replaceAll(">", "");
		System.out.println("title:" + title);
		return title;
	}
	public static int imageCounter = 1;
	static void downloadImages(Elements elements, String title)
			throws IOException {
		if (elements == null || elements.size() == 0) {
			return;
		}
		String imageA = new Integer(imageCounter++).toString() + "_" + title;
		for (int i = 0; i < elements.size(); i++) {
			Element eachElement = elements.get(i);
			String imageUrl = toURL(eachElement.attr("src"));
			System.out.println("imageurl:" + imageUrl);
			String imageName = null;
			if (elements.size() == 1) {
				imageName = imageA;
			} else {
				imageName = imageA + "_" + new Integer(i + 1).toString();
			}
			try {
				downloadImage(imageUrl, imageName);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	private static String getFileExtension(String filepath) {
		if (filepath == null) {
			return "";
		}
		return filepath.substring(filepath.lastIndexOf(".")+1, filepath.length());
	}

	private static void downloadImage(String urlString, String imageName)
			throws IOException {
		String extension = getFileExtension(urlString);
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		con.setConnectTimeout(1000 * 60);
		con.setReadTimeout(1000 * 60);
		// 输入流
		InputStream is = con.getInputStream();
		// 1K的数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		OutputStream os = new FileOutputStream(saveTo +(imageCounter++)+"." +imageName + "."
				+ extension);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
		System.out.println("download: "+imageName +" url:"+urlString);
	}
}
